//
//  CustomCameraVC.m
//  MTime
//
//  Created by mtime_lee on 2017/8/28.
//  Copyright © 2017年 imac. All rights reserved.
//

#import "CustomCameraVC.h"
//#import "CustomCameraPreview.h"

 #import "CustomCameraShootPreview.h"
#import "MZCamera.h"
#import "CameraImageRecognizeModel.h"
#import "UIImage+Extension.h"
//#import "ImageIdentifierResultVC.h"//图像识别结果展示VC
#import <TZImagePickerController/TZImagePickerController.h>
#import "PhotoTweaksViewController.h"
#define kURL_ImageRecognition @"/app/recognition"
#import "NetworkEngine.h"
#import "NetworkEngine+imageCloudManager.h"
#import "GoodsModel.h"
#import "MainDefaulSearctVC.h"

typedef NS_ENUM(NSUInteger, CameraPreviewButtonType) {
    CameraPreviewButtonTypeBack = 101,
    CameraPreviewButtonTypePhotoAlbum,
    CameraPreviewButtonTypeCameraShutter,
    CameraPreviewButtonTypeSwitchCamera,
    CameraPreviewButtonTypeImageSave,
    CameraPreviewButtonTypeImageRegain
};



//static CGFloat buttonOffsetCenterX = 80.0f; // 按钮偏移量

@interface CustomCameraVC () <CustomCameraShootPreviewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, PhotoTweaksViewControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *picker;

@property (nonatomic, assign) CameraPreviewButtonType previewButtonType;
@property (nonatomic, strong) MZCamera *camera;
@property (nonatomic, strong) CustomCameraShootPreview *preview;

@property (nonatomic, copy) CameraImageBlock imageCallback;

@end

@implementation CustomCameraVC {
    
    // 记录当前是否取消了图片识别(网络请求)
//    BOOL _isCancelImageRecognize;
    
    UIButton    *_backButton;
    UIButton    *_photoAlbumButton;
    UIButton    *_shutterButton;
    UIButton    *_switchButton;
    
    UIButton    *_imageSaveButton;
    UIButton    *_imageRegainButton;
    UIImageView *_shutterImageView; //快门的照片
    
    //    UILabel     *_positionTipsLabel;
    UIView      *_photoSeletedToolsBGView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setNavigationBarHide];
//    [self.statusBarView setHidden:NO];
    
    
    if ([Tools devicePermissionForCamera]) {
        [self.camera start];
    }  
}

//- (BOOL)prefersStatusBarHidden {
//    return YES;
//}

#pragma mark - 当前识别状态
- (void)_setRecognizeStatus:(BOOL)isRecognize {
    isRecognize == YES ? ^(){
        [self.camera stop];
        [self.preview isImageRecognize:YES];
    }() : ^(){
        [self.camera start];
        [self.preview isImageRecognize:NO];
    }();
}
#pragma mark - Getter
- (CustomCameraShootPreview *)preview {
    if (!_preview) {
//        _preview = [[CustomCameraShootPreview alloc] initWithFrame:self.view.frame delegate:self];
        //        [_preview setBackgroundColor:[UIColor redColor]];
        _preview = [CustomCameraShootPreview instanceWithFrame:self.view.bounds];
        _preview.delegate = self;
        [self.view insertSubview:_preview atIndex:0];
    }
    return _preview;
}

- (MZCamera *)camera {
    if (!_camera) {
        _camera = [[MZCamera alloc] initWithPreView:self.preview.cameraPreview preViewFrame:self.view.bounds];
    }
    return _camera;
}

/////  临时
- (void)shootCameraBtnCallback {
    if (self.imageCallback) {
        [self.camera captureImageCompletion:^(UIImage *image) {
            self.imageCallback(UIImagePNGRepresentation(image), 0);
        }];
    }
    
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    PhotoTweaksViewController *photoTweaksViewController = [[PhotoTweaksViewController alloc] initWithImage:image];
    photoTweaksViewController.delegate = self;
    photoTweaksViewController.autoSaveToLibray = NO;
//    photoTweaksViewController.autoSaveToLibray = YES;
//    photoTweaksViewController.maxRotationAngle = M_PI_4;
    [picker pushViewController:photoTweaksViewController animated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - PhotoTweaksViewControllerDelegate
/**
 Called on image cropped.
 */
- (void)photoTweaksController:(PhotoTweaksViewController *)controller didFinishWithCroppedImage:(UIImage *)croppedImage {
    [controller.navigationController popToRootViewControllerAnimated:YES];
    [self imagePickerControllerDidCancel:self.picker];
//    [self.camera stop];
    // 设置拍照识别中
//    [self.preview isImageRecognize:YES];
    [self _setRecognizeStatus:YES];
    [self.preview.albumMaskView setHidden:NO];
    [self.preview.albumImageView setImage:croppedImage];
    
//    self.preview.albumImage = croppedImage;
    [self _getImageURLWithImage:croppedImage];
}

/**
 Called on cropping image canceled
 */
- (void)photoTweaksControllerDidCancel:(PhotoTweaksViewController *)controller {
    [controller.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark - CustomCameraPreviewDelegate
- (void)customCameraButtonClickWithType:(CustomCameraButtonType)type {
    
    switch (type) {
        case CustomCameraButtonTypePop:{
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        case CustomCameraButtonTypeAlbum:{
                // 相册
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.allowsEditing = NO;
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.navigationBarHidden = YES;
            self.picker = picker;
            [self.navigationController presentViewController:picker animated:YES completion:nil];
        }
            break;
        case CustomCameraButtonTypeTakePhoto:{
            // 相机获取图片
            __weak __typeof(self)weakSelf = self;
            [self.camera captureImageCompletion:^(UIImage *image) {
                [self.preview.albumMaskView setHidden:YES];
//                [self.preview.albumImageView setImage:croppedImage];
                // 拍照回调
//                _isCancelImageRecognize = NO;
//                [weakSelf.camera stop];
                [weakSelf _setRecognizeStatus:YES];
                CGRect frame = weakSelf.preview.clipRect;

                UIImage *clipImage = [[image fixOrientation] qmui_imageWithClippedRect:frame];
  
                [weakSelf _getImageURLWithImage:clipImage];
            }];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 根据图片获取图片URL
- (void)_getImageURLWithImage:(UIImage *)image {
    //上传到腾讯云获取图片地址
    __weak __typeof(self)weakSelf = self;
    
    /* TODO: ================= 上传到腾讯云获取图片地址 =================*/

    
    [kNetworkShared getImageURLWithImage:image completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
        if (isSuccess && filePath && fileName) {
            NSString *imageURL = kSTRING_FORMAT(@"%@/%@",filePath,fileName);
            [weakSelf _requestImageRecognitionWithImage:image imageURL:imageURL];

        } else {
            // 识别失败的情况
            [weakSelf _setRecognizeStatus:NO];
        }
    }];

}

#pragma mark - 请求图片识别
- (void)_requestImageRecognitionWithImage:(UIImage *)image imageURL:(NSString *)imageURL {
    
    /* TODO: ================= 获取识别后数据 =================*/

//     kShowLoadingView5Delay
    __weak __typeof(self)weakSelf = self;
    
//    self = imageURL
//    img/goods/499f581c52a842928b2d4ef6eea4769a.jpg"
    
    
    [[serviceDefualt loadAdviserDataImgUrl:imageURL reponseObjctClass:[goodVOsModel class]]subscribeNext:^(ResponseData * x) {
        if (x.success) {
            /* TODO: ================= 添加等待图标 =================*/
            NSMutableArray *arrM = [[NSMutableArray alloc]init];
            NSArray *arr = x.responseRawData[@"data"];
            if (arr.count!=0) {
                for (NSDictionary *dic in  arr) {
                    goodVOsModel *model = [goodVOsModel yy_modelWithJSON:dic];
                    [arrM addObject:model];
                }
            }
            /** 图像识别 */
            MainDefaulSearctVC *vc = [[MainDefaulSearctVC alloc]init];
            vc.indexType = 2;
            vc.arrImageM = arrM;
            vc.search.leb.text = [NSString stringWithFormat:@"%lu个图像识别结果",(unsigned long)arrM.count];
            [self.navigationController pushViewController:vc animated:YES];
            
        } else {
             [Tools showTips:x.errorInfo];
        }
        
        [weakSelf _setRecognizeStatus:NO];
    }];
 
    

    

}


#pragma mark - 记录imageBlock
- (void)getCameraImageCallback:(CameraImageBlock)callback {
    self.imageCallback = callback;
}

#pragma mark - 生命周期
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
//    [self.preview layoutIfNeeded];
    [self.preview.cameraPreview layoutIfNeeded];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setStatusBar:(UIStatusBarStyleLightContent)];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    [self.camera start];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
//    [self.camera stop];
    
//    [kNetworkShared.operationQueue cancelAllOperations];
//    _isCancelImageRecognize = NO;
}

@end
